{% extends 'layout/layui_base_page.html' %}

{% load static %}

<!-- Title -->
{% block title %} 阶段和阶段内容管理 {% endblock %}

<!-- CSS -->
{% block css %}
    <style>
        .layui-card {
            border: 1px solid lightgray;
            box-sizing: border-box;
            height: 350px;
        }

        .layui-card:hover {
            box-shadow: 0 0 8px rgba(0, 0, 0, 0.2);
        }
       .contentItem:hover {
            background-color: rgba(0, 0, 0, 0.1);
        }


    </style>
{% endblock %}


<!-- Content -->
{% block content %}
    <!-- 内容01： 显示当前的line、department、position  -->
    <div id="basicInfo" style="padding: 20px;">
        <form class="layui-form">
            {% csrf_token %}
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="line"><b>产线：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" id="line" name="line" class="layui-input" readonly
                               style="background-color: #eaeaea">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" for="department"><b>部门：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" id="department" name="department" class="layui-input" readonly
                               style="background-color: #eaeaea">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" for="position"><b>职位：</b></label>
                    <div class="layui-input-inline" style="display: none">
                        <input type="text" id="position_id" name="position_id" class="layui-input" readonly
                               style="display: block">
                    </div>
                    <div class="layui-input-inline">
                        <input type="text" id="position" name="position" class="layui-input" readonly
                               style="background-color: #eaeaea">
                    </div>
                </div>

                <div class="layui-inline">
                    <button type="button" id="btnAdd" class="layui-btn"><i class='fa fa-plus-circle'
                                                                           aria-hidden='true'></i>&nbsp 添加阶段
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- 内容02. 展示阶段和阶段内容 -->
    <div class="layui-bg-gray">
        <div id="phaseArea" class="layui-row layui-col-space15">

        </div>
    </div>

    <!-- 内容03：添加阶段的弹出层  -->
    <div id="addPhaseLayer" style="display: none;padding: 20px">
        <form class="layui-form">
            {% csrf_token %}
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="phase"><b>阶段：</b></label>
                    <div class="layui-input-inline">
                        <div id="phase" class="xm-select-demo"></div>
                    </div>
                </div>
            </div>
        </form>
    </div>

{% endblock %}

<!-- JS -->
{% block js %}
    <script src="{% static 'js/xm-select.js' %}"></script>
    <script>

        // 入口函数
        $(function () {
            // 初始化页面
            initPage();
            // 相应按钮的点击
            buttonClick();
            // 初始化xmselect
            initXMSelect();

        });

        // =============== 初始化页面具体实现 ==========
        function initPage() {
            layui.use(['element'], function () {
                var element = layui.element;
            });

            // 接收父页面的传递数据
            let position_info = parent.INFOS;
            // 赋值
            $('#line').val(position_info.line_name);
            $('#department').val(position_info.name);
            $('#position_id').val(position_info.position_id);
            $('#position').val(position_info.position_name);

            // 获取当前职位的阶段和阶段内容
            $.ajax({
                //url: get_phase_phasecontent_by_position
                url: "{% url 'get_phase_phasecontent_info' %}"
                , method: 'post'
                , data: {
                    position_id: position_info.position_id,
                    csrfmiddlewaretoken: "{{ csrf_token }}"
                }
                , success: function (res) {
                    console.log(res);
                    // 展示阶段和阶段内容
                    buildPhase(res.data);
                }
            })
        }

        // ============== 初始化xmselect ===============
        function initXMSelect() {
            let phase_select = xmSelect.render({
                el: '#phase',
                name: 'phase',
                layVerify: 'required',
                layVerType: 'msg',
                radio: true,
                clickClose: true,
                tips: '请选择要添加的阶段',
                filterable: true,
                height: '200px',
                width: '100px',
                data: [],
            });
            // Ajax获取要添加的阶段
            $.ajax({
                // url: get_next_phase
                url: "{% url 'get_next_phase' %}"
                , method: 'post'
                , data: {
                    position_id: $('#position_id').val(),
                    csrfmiddlewaretoken: "{{ csrf_token }}"
                }
                , success: function (res) {
                    // 为下拉框提供选项
                    phase_select.update({
                        data: res.data,
                    });
                    // 选中当前的值
                    //phase_select.setValue([1]);
                }
            })
        }

        // ============== 相应按钮的点击 ====================
        function buttonClick() {
            // 添加阶段
            $('#btnAdd').on('click', function () {
                // 获取当前职位的编号
                let position_id = $('#position_id').val();
                // 跳出弹出层提示输入阶段的数量
                layui.use(['layer'], function () {
                    let layer = layui.layer;
                    layer.open({
                        type: 1
                        , title: "<b style='color:navy'>【添加阶段】</b>"
                        , area: ['400px', '400px']
                        , btn: ['确认', '取消']
                        , content: $('#addPhaseLayer')


                        // ===== 回调函数 ====
                        , yes: function (index, layero) {
                            $.ajax({
                                //url: add_phase
                                url: "{% url 'add_position_phase' %}"
                                , method: 'post'
                                , data: {
                                    position_id: position_id,
                                    phasename_id: xmSelect.get('#phase', true).getValue('valueStr'),
                                    csrfmiddlewaretoken: "{{ csrf_token }}"
                                }
                                , success: function (res) {
                                    if (res.status) {
                                        layer.close();
                                        location.reload();
                                    } else {
                                        layui.layer.msg(res.error);
                                    }
                                }
                            })
                        }

                    })

                })
            });

            // 删除阶段
            $('body').on('click', '.delPhase', function () {
                // 取出当前的阶段编号和名称
                let phase_id = $(this).attr('id');
                let phase_name = $(this).attr('name');
                layui.use(['layer'], function () {
                    let layer = layui.layer;
                    layer.confirm("您确定要删除阶段信息【" + phase_name + "】吗？", {
                        icon: 3, btn: ['确认', '取消']
                    }, function (index) {
                        $.ajax({
                            //url: del_phase
                            url: "{% url 'del_position_phase' %}"
                            , method: 'post'
                            , data: {
                                phase_id: phase_id,
                                csrfmiddlewaretoken: "{{ csrf_token }}"
                            }
                            , success: function (res) {
                                if (res.status) {
                                    location.reload();
                                } else {
                                    layui.layer.msg(res.error,{
                                        icon:2, area:['400px','200px'], time:-1, btn:['关闭']
                                    });
                                }
                            }
                        })
                    })
                })
            });

            // === 添加阶段内容 ===
            $('body').on('click', '.addPhaseContent', function () {
                // 获取当前部门的Id
                let phase_id = $(this).attr("id");

                layui.use(['layer'], function () {
                    let layer = layui.layer;

                    layer.prompt({
                        title: "输入要添加的阶段内容，点击确定"
                        , formType: 0
                        , area: ['600px', '200px']
                    }, function (value, index, elem) {
                        // Ajax
                        $.ajax({
                            url: "{% url 'add_position_phase_phasecontent' %}"
                            , method: 'post'
                            , data: {
                                phase_id: phase_id,
                                phasecontent_name: value,
                                csrfmiddlewaretoken: "{{ csrf_token }}"
                            }
                            , success: function (res) {
                                if (res.status) {
                                    layui.layer.msg("阶段内容添加成功！");
                                    location.reload()
                                } else {
                                    layui.layer.msg(res.error, {
                                        icon: 2, area: ['400px', '200px'], time: -1, btn: ['关闭']
                                    })
                                }
                            }
                        })
                    })
                });

            });

             // === 编辑阶段内容 ===
            $('body').on('click', '.editPhaseContent', function () {
                // 获取当前部门的Id
                let phase_id = $(this).attr("tag");
                let phasecontent_id = $(this).attr("id");
                let phasecontent_name = $(this).attr("name");
                layui.use(['layer'], function () {
                    let layer = layui.layer;

                    layer.prompt({
                        title: "输入要修改的阶段内容，点击确定"
                        , value: phasecontent_name
                        , formType: 0
                    }, function (value, index, elem) {
                        // Ajax
                        $.ajax({
                            url: "{% url 'edit_position_phase_phasecontent' %}"
                            , method: 'post'
                            , data: {
                                phase_id: phase_id,
                                phasecontent_id: phasecontent_id,
                                phasecontent_name: value,
                                csrfmiddlewaretoken: "{{ csrf_token }}"
                            }
                            , success: function (res) {
                                if (res.status) {
                                    layui.layer.msg("阶段内容修改成功！");
                                    location.reload()
                                } else {
                                    layui.layer.msg(res.error, {
                                        icon: 2, area: ['400px', '200px'], time: -1, btn: ['关闭']
                                    })
                                }
                            }
                        })
                    })
                });

            });

            // === 删除阶段内容 ===
            $('body').on('click', '.delPhaseContent', function () {
                // 获取当前部门的名字和Id
                let phasecontent_id = $(this).attr('id');
                let phasecontent_name = $(this).attr('name');
                // 提示
                let confirmStr = "您确定要删除阶段内容【名称：" + phasecontent_name + "】的信息吗？";
                // 使用layui.layer
                layui.use(['layer'], function () {
                    let layer = layui.layer;

                    layer.confirm(confirmStr, {
                        icon: 3, area: ['400px', '200px'], btn: ['确认', '取消']
                    }, function (index) {
                        // ajax请求
                        $.ajax({
                            url: "{% url 'del_position_phase_phasecontent' %}"
                            , method: 'post'
                            , data: {
                                phasecontent_id: phasecontent_id,
                                csrfmiddlewaretoken: "{{ csrf_token }}"
                            }
                            , success: function (res) {
                                if (res.status) {
                                    layui.layer.msg("阶段内容删除成功！");
                                    location.reload()
                                } else {
                                    layui.layer.msg(res.error, {
                                        icon: 2, area: ['400px', '200px'], time: -1, btn: ['关闭']
                                    })
                                }
                            }
                        })
                    })
                })
            });
        }

        // ================= 构建阶段信息的的前端展示 =================
        function buildPhase(data) {
            // 获取顶级的父容器
            let topContainer = $('#phaseArea');
            //清空
            topContainer.empty();
            // 开始遍历数据
            $.each(data, (index, value) => {
                // 新建一层div
                let oneLevelDiv = $('<div>').attr({'class': 'layui-col-md4',}).appendTo(topContainer);
                // 新建二层div
                let twoLevelDiv = $('<div>').attr({
                    'class': 'layui-card',
                    'style': 'height:550px;background-color:#F3F3FA',
                }).appendTo(oneLevelDiv);
                // 新建卡片的标题
                let cardTitle = $('<div>').attr({
                    'class': 'layui-card-header layui-row',
                    'style': 'border-bottom: 1px solid grey'
                }).appendTo(twoLevelDiv);
                // 新建卡片标题
                let cardTitleName = $('<div>').attr({'class': 'layui-col-lg6'}).html("<b style='color:darkred;font-size：18px'>" + value.phasename__name + "</b>").appendTo(cardTitle);
                let cartTitleButton = $('<div>').attr({
                    'class': 'layui-col-lg6',
                    style: 'text-align:right;'
                }).appendTo(cardTitle);
                $('<a>').attr({
                    href: "javascript:;",
                    class: 'layui-btn layui-btn-xs layui-btn-danger delPhase',
                    id: value.id,
                    name: value.phasename__name,
                    title: '删除阶段'
                }).html("<i class='fa fa-trash' aria-hidden='true'></i>").appendTo(cartTitleButton);
                // 新建第三个按钮
                $('<a>').attr({
                    href: "javascript:;",
                    class: 'layui-btn layui-btn-xs addPhaseContent',
                    id: value.id, // 内容Id
                    title: '添加阶段内容'
                }).html("<i class='fa fa-plus-circle' aria-hidden='true'></i>&nbsp 内容").appendTo(cartTitleButton);
                // 新建卡片的内容
                let cardBody = $('<div>').attr({'class': 'layui-card-body'}).html(buildPhaseContent(value)).appendTo(twoLevelDiv)
            })
        }

        // ================= 构建阶段具体内容的前端展示 =================
        function buildPhaseContent(phasecontent_data) {
            // 新建ul标签
            let ulContainer = $('<ul>');
            console.log("=========",phasecontent_data);
            // 遍历数据
            $.each(phasecontent_data.content, (index, value) => {
                let liContainer = $('<li>').attr({
                    'class': 'contentItem',
                    style: "line-height: 30px;",
                }).appendTo(ulContainer);
                // 栅格系统的div
                let row = $('<div>').attr({'class': 'layui-row'}).appendTo(liContainer);
                // 左边的标题
                let row_left = $('<div>').attr({'class': 'layui-col-lg10 contentName'}).html("<i class='fa fa-certificate' aria-hidden='true'></i> &nbsp " +
                    "<a href='javascript:;' title='" + value.name + "'>" + value.name + "</a>").appendTo(row);
                // 右边的三个按钮
                let row_right = $('<div>').attr({'class': 'layui-col-lg2', 'style': 'text-align:right;'}).appendTo(row);
                // 新建第一个按钮 --- 编辑
                $('<a>').attr({
                    href: "javascript:;",
                    class: 'layui-btn layui-btn-xs layui-btn-normal editPhaseContent',
                    id: value.id,
                    name: value.name,
                    tag: phasecontent_data.id,
                    title: '编辑职位'
                }).html("<i class='fa fa-edit' aria-hidden='true'></i>").appendTo(row_right);
                // 新建第二个按钮 --- 删除
                $('<a>').attr({
                    href: "javascript:;",
                    class: 'layui-btn layui-btn-xs layui-btn-danger delPhaseContent',
                    id: value.id,
                    name: value.name,
                    title: '删除职位'
                }).html("<i class='fa fa-trash' aria-hidden='true'></i>").appendTo(row_right)
            });

            return ulContainer

        }
    </script>
{% endblock %}